import 'package:dio/dio.dart';
import 'http_dio.dart';
class AuthInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    // 排除登录/注册等不需要token的接口
    if (!options.path.contains('/auth')) {
      final token = await _getToken();
      if (token != null) {
        options.headers['Authorization'] = 'Bearer $token';
      }
    }
    super.onRequest(options, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) async {
    // 处理401未授权错误，尝试刷新token
    if (err.response?.statusCode == 401) {
      try {
        final newToken = await _refreshToken();
        if (newToken != null) {
          // 更新header后重试请求
          err.requestOptions.headers['Authorization'] = 'Bearer $newToken';
          final response = await HttpManager().getDio.fetch(err.requestOptions);
          return handler.resolve(response);
        }
      } catch (e) {
        handler.next(err);
      }
    }
    super.onError(err, handler);
  }

  Future<String?> _getToken() async {
    // 从本地存储获取token
    return 'your_access_token';
  }

  Future<String?> _refreshToken() async {
    // 实现token刷新逻辑
    return 'new_refreshed_token';
  }
}